﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Linq;
using Corina.Commands;
using System.Net.NetworkInformation;

namespace Corina.Cydee.Apphub.Viewmodels
{
    public class HomeViewmodel : ViewmodelBase
    {
        public HomeViewmodel() {
            DeviceMeasureClient.GetAllDeviceMessageCompleted += GetAllDeviceMessageCompleted;
            DataContext.AccountChanged+=AccountChanged;
            if(DataContext.IsValid&&ShowUnresolvedOnHome)
            {
                LoadData();
            }
        }

        private void AccountChanged(object sender, EventArgs e)
        {
            if (DataContext.IsValid&&ShowUnresolvedOnHome)
            {
                LoadData();
            }
        }

        private void GetAllDeviceMessageCompleted(object sender, DataService.GetAllDeviceMessageCompletedEventArgs e)
        {
            if(e.Error == null)
            {
                UnresolvedCount = e.Result.TotalCount;
                if(UnresolvedCount>0)
                {
                    MessageContent = e.Result.DataObjects.FirstOrDefault()["Content"] as string;
                }
            }
        }

        protected override void LoadData(params object[] paras)
        {
            DeviceMeasureClient.GetAllDeviceMessageAsync(Account, Password, "", 0, "", false, 1, 1);
        }

        public string CurrentOS
        {
            get
            {
                OperatingSystem os = Environment.OSVersion;
                return string.Format("{0} {1}", os.Platform, os.Version);
            }
        }

        #region Properties
        private bool _showSettingPanel = false;
        public bool ShowSettingsPanel
        {
            get { return _showSettingPanel; }
            set
            {
                _showSettingPanel = value;
                RaisePropertyChanged(() => ShowSettingsPanel);
            }
        }

        public bool ShowUnresolved
        {
            get
            {
                return UnresolvedCount > 0;
            }
        }

        private bool _showUnresolvedOnHome = true;
        public bool ShowUnresolvedOnHome
        {
            get { return _showUnresolvedOnHome; }
            set
            {
                _showUnresolvedOnHome = value;
                RaisePropertyChanged(() => ShowUnresolvedOnHome);
                if(ShowUnresolvedOnHome)
                {
                    LoadData();
                }
                else
                {
                    UnresolvedCount = 0;
                }
            }
        }

        private int _unresolvedCount = 0;
        public int UnresolvedCount
        {
            get { return _unresolvedCount; }
            set
            {
                _unresolvedCount = value;
                RaisePropertyChanged(() => UnresolvedCount);
                RaisePropertyChanged(() => GotoResolveCommand);
                RaisePropertyChanged(() => ShowUnresolved);
            }
        }

        private string _messageContent = string.Empty;
        public string MessageContent
        {
            get { return _messageContent; }
            set
            {
                _messageContent = value;
                RaisePropertyChanged(() => MessageContent);
            }
        }
        #endregion

        #region OOB
        public bool IsRunningOutOfBrowser
        {
            get
            {
                return App.Current.IsRunningOutOfBrowser;
            }
        }

        public ICommand InstallOOBCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !IsRunningOutOfBrowser; },
                    ExecuteCallback = delegate {
                        if (!App.Current.IsRunningOutOfBrowser && App.Current.InstallState == InstallState.NotInstalled)
                        {
                            App.Current.Install();
                            App.Current.InstallStateChanged += Current_InstallStateChanged;
                        }
                    }
                };
            }
        }

        public ICommand ChechUpdateCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return IsRunningOutOfBrowser && NetworkInterface.GetIsNetworkAvailable(); },
                    ExecuteCallback = delegate
                    {
                        App.Current.CheckAndDownloadUpdateCompleted += CheckAndDownloadUpdateCompleted;
                        App.Current.CheckAndDownloadUpdateAsync();
                    }
                };
            }
        }

        private void CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
            {
                MessageBox.Show("更新完毕，请重新启动程序！");
            }
            else
            {
                if (e.Error == null)
                    MessageBox.Show("程序无更新（如果有新更新要修改 Assembly Version）");
                else
                    MessageBox.Show(e.Error.Message);
            }
        }

        private void Current_InstallStateChanged(object sender, EventArgs e)
        {
            RaisePropertyChanged(() => IsRunningOutOfBrowser);
        }

        protected override void NetworkChanged()
        {
            
        }
        #endregion

        #region Command
        public ICommand GotoResolveCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return UnresolvedCount > 0; },
                    ExecuteCallback = delegate {
                        DataContext.GotoView("CYDEE_MEASURE_DEVICEMESSAGE");
                    }
                };
            }
        }
        #endregion
    }
}
